<?php

namespace App\Admin\Models;
use App\Admin\Utils\Admin;
use Illuminate\Database\Eloquent\SoftDeletes;

class AdminPermission extends Model
{
    use SoftDeletes;

    protected $guarded = []; 

    public $casts = [
        'id' => 'string',
        'name' => 'string',
        'slug' => 'string',
        'http_method' => 'string',
        'http_path' => 'string',
        'created_at' => 'datetime:Y-m-d H:i:s',
        'updated_at' => 'datetime:Y-m-d H:i:s',
        'deleted_at' => 'datetime:Y-m-d H:i:s',
    ];

    protected $fillable = ['name', 'slug', 'http_method', 'http_path'];
    
    public static $httpMethods = [
        'GET', 'POST', 'PUT', 'DELETE', 'PATCH', 'OPTIONS', 'HEAD',
    ];

    // 添加角色时默认赋的基本权限
    public static $basicPermission = [
        'pass-getInnerTitle',
        'pass-field',
        'pass-get-system-media',
        'pass-post-system-media',
    ];

    public function setHttpMethodAttribute($method)
    {
        if (is_array($method)) {
            $this->attributes['http_method'] = implode(',', $method) ?: null;
        } else {
            $this->attributes['http_method'] = $method;
        }
    }

    public function getHttpMethodAttribute($method)
    {
        return array_filter(explode(',', $method));
    }

    public function setHttpPathAttribute($httpPath)
    {
        if (is_array($httpPath)) {
            $this->attributes['http_path'] = implode("\n", $httpPath) ?: null;
        } else {
            $this->attributes['http_path'] = $httpPath;
        }
    }

    public function getHttpPathAttribute($httpPath)
    {
        return array_filter(explode("\n", $httpPath));
    }

    public function roles()
    {
        return $this->belongsToMany(
            AdminRole::class,
            'admin_role_permission',
            'role_id',
            'permission_id'
        );
    }

    public function existAdminPermission($slug){
        return $this->where('slug',$slug)->first();
    }

    public static function checkAdminPermission($tableName, $method)
    {
        if (Admin::isAdministrator()) {
            return true;
        }
        $allPermissions = Admin::user()->allPermissions();
        foreach ($allPermissions as $key => $value) {
            if (
                in_array("/{$tableName}*", $value['http_path']) && 
                in_array($method, $value['http_method'])
            ) {
                return true;
            }
        }
        return false;
    }
}
